import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * @author sk.z
 */
public class DrawCoordinate extends JApplet {
    private static final long serialVersionUID = 7199803776256352698L;

    private static final int WIDTH = 800;
    private static final int HEIGHT = 800;
    private static final int ORIGIN_X = 400;
    private static final int ORIGIN_Y = 400;

    public static void main(String[] args) {
        JFrame jFrame = new JFrame("Draw Coordinate");

        JApplet applet = new DrawCoordinate();
        jFrame.getContentPane().add("Center", applet);

        jFrame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        jFrame.setSize(new Dimension(WIDTH, HEIGHT));
        jFrame.setResizable(false);
        jFrame.setVisible(true);
    }

    public void init() {
        setBackground(Color.white);
        setForeground(Color.black);
    }

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        drawCoordinateLine(g2);

        g2.setColor(Color.GREEN);
        Equation X_ADD_Y_EQ1 = new Equation();
        int y;
        for (int x = -400; x < WIDTH; x++) {
            y = X_ADD_Y_EQ1.getY(x);
            drawPoint(g2, transX(x), transY(y));
        }

    }

    //绘制坐标轴线
    private void drawCoordinateLine(Graphics2D graphics) {
        graphics.drawLine(0, ORIGIN_Y, WIDTH, ORIGIN_Y);
        graphics.drawLine(ORIGIN_X, 0, ORIGIN_X, HEIGHT);
    }

    //转换系坐标到屏幕坐标
    private int transX(int x) {
        return x + ORIGIN_X;
    }

    private int transY(int y) {
        return y + ORIGIN_Y;
    }

    private void drawPoint(Graphics2D graphics, int x, int y) {
        graphics.drawLine(x, y, x, y);
    }

    private static class Equation {
        // x + y = 5;
        private int getY(int x) {
            return 5 - x;
        }
    }

}
